<template>
  <div class="userManage">
    <search-form
      ref="header"
      :search-data="ruleForm"
      :search-form="searchData"
      :search-handle="searchHandle"
    ></search-form>

    <base-table
      :tableData="tableData"
      :tableColumn="tableTitle"
      :Pagination="page"
      :tableOption="tableOption"
      :height="tableHeight"
      @handleSizeChange="handleSizeChange"
      @handleCurrentChange="handleCurrentChange"
      @action="handleButton"
    ></base-table>

    <!-- 添加或编辑弹框 -->
    <addOrEditDialog
      ref="energyDialog"
      v-if="dialogObj.show"
      :Visible="dialogObj.show"
      :type="dialogObj.type"
      :heatSourceId="ruleForm.heatSourceId"
      :dialogRow="dialogObj.dialogRow"
      @close="dialogObj.show = false"
      @refresh="refreshTable"
    ></addOrEditDialog>
  </div>
</template>
<script>
import baseTable from "@/components/Table/index.vue";
import searchForm from "@/components/SearchForm/index.vue";
import addOrEditDialog from "./component/addOrEditDialog.vue";
import { getEnergyData, delEnergy } from "@/api/energy.js";
import { useStore } from "vuex";
import { getHeatStation } from "@/api/heatStation";
import { getSystemList } from "@/api/system";
import { reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import heightMinxin from "@/utils/tableHeight.mixin";
export default {
  name: "user",
  mixins: [heightMinxin],
  components: {
    searchForm,
    baseTable,
    addOrEditDialog,
  },
  setup() {
    const store = useStore();
    const state = reactive({
      ruleForm: {
        heatSourceId: "",
        heatStationId: "",
        heatSystemId: "",
        type: 1,
        name: "",
      },
      searchData: [
        {
          type: "Select",
          prop: "heatSourceId",
          options: [],
          placeholder: "选择热源",
          change: () => {
            getHeatStationData();
          },
        },
        {
          type: "Select",
          prop: "heatStationId",
          options: [],
          placeholder: "选择换热站",
          change: () => {
            getSystemData();
          },
        },
        {
          type: "Select",
          prop: "heatSystemId",
          options: [],
          placeholder: "选择系统",
          change: () => {},
        },
        {
          type: "Select",
          prop: "type",
          options: [
            { label: "气", value: 1 },
            { label: "水", value: 2 },
            { label: "电", value: 3 },
            { label: "热", value: 4 },
          ],
          placeholder: "选择类型",
          change: () => {},
        },
        {
          type: "Input",
          prop: "name",
          placeholder: "输入名称进行搜索",
        },
      ],
      searchHandle: [
        {
          label: "搜索",
          type: "primary",
          handle: () => {
            getListData();
          },
        },
        {
          label: "添加",
          handle: () => {
            const {
              heatSourceId,
              heatStationId,
              heatSystemId,
              type,
            } = state.ruleForm;
            if (heatSourceId == "") {
              return ElMessage.error("热源不能为空");
            }
            handleAdd("add", {
              heatSourceId,
              heatStationId,
              heatSystemId,
              type,
            });
          },
        },
      ],
      tableData: [],
      tableTitle: [
        { prop: "heatSourceName", label: "热源名称" },
        { prop: "heatStationName", label: "换热站" },
        { prop: "heatSystemName", label: "系统" },
        { prop: "name", label: "名称" },
        {
          prop: "type",
          label: "类型",
          render(h) {
            if (h.type == 1) {
              return "气";
            } else if (h.type == 2) {
              return "水";
            } else if (h.type == 3) {
              return "电";
            } else {
              return "热";
            }
          },
        },
        { prop: "unit", label: "单位" },
        { prop: "rate", label: "倍率" },
      ],
      tableOption: {
        label: "操作",
        buttons: [
          { name: "编辑", methods: "edit" },
          { name: "删除", methods: "delete", style: { color: "red" } },
        ],
      },
      page: {
        pageNo: 1,
        pageSize: 10,
        total: 0,
      },
      currentIdx: null,
      dialogObj: { show: false, type: "add", dialogRow: {} },
    });

    onMounted(async () => {
      await getHeatSourceData();
      getListData();
    });
    const getHeatSourceData = () => {
      const { sourceData } = store.getters;
      state.searchData[0].options = sourceData;
      state.ruleForm.heatSourceId = sourceData ? sourceData[0].value : "";
      getHeatStationData();
      getSystemData();
    };
    const getHeatStationData = () => {
      state.ruleForm.heatStationId = "";
      state.searchData[1].options = [];
      if (state.ruleForm.heatSourceId == "") {
        state.ruleForm.heatStationId = "";
        state.searchData[1].options = [];
        return;
      }

      getHeatStation({ heatSourceId: state.ruleForm.heatSourceId }).then(
        (res) => {
          if (res.data.success) {
            const { data } = res.data;
            const list = data.map((item) => {
              return { label: item.name, value: item.id };
            });
            state.searchData[1].options = list;
          }
        }
      );
    };

    const getSystemData = async () => {
      state.ruleForm.heatSystemId = "";
      state.searchData[2].options = [];
      const { heatSourceId, heatStationId } = state.ruleForm;
      const { data: res } = await getSystemList({
        heatSourceId,
        heatStationId,
      });
      if (res.success) {
        if (res.data) {
          const list = res.data.map((item) => {
            return { label: item.name, value: item.id };
          });
          state.searchData[2].options = list;
        }
      }
    };
    /**
     * 查询
     */
    const getListData = async () => {
      let params = Object.assign(state.ruleForm, {
        pageNo: state.page.pageNo,
        pageSize: state.page.pageSize,
      });
      const { data: response } = await getEnergyData(params);
      if (response.success) {
        const { total, res } = response.data;
        state.tableData = res;
        state.page.total = total;
      }
    };
    const handleCurrentChange = (val) => {
      state.page.pageNo = val;
      getListData();
    };
    const handleSizeChange = (val) => {
      state.page.pageSize = val;
      getListData();
    };
    /***
     * 添加
     */
    const handleAdd = (type, row) => {
      state.dialogObj.show = true;
      state.dialogObj.type = type;
      state.dialogObj.dialogRow = row;
    };
    /**
     * 编辑和删除
     */
    const handleButton = ({ row, methods, index }) => {
      if (methods == "edit") {
        state.currentIdx = index;
        handleAdd(methods, row);
      } else {
        handleDelete(row, index);
      }
    };

    const handleDelete = (row, index) => {
      ElMessageBox.confirm(`确定删除该用户${row.name}?`, "提示", {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          delEnergy({ id: row.id }).then((res) => {
            if (res.data.success) {
              state.tableData.splice(index, 1);
              ElMessage.success(res.data.msg);
            }
          });
        })
        .catch(() => {});
    };

    const refreshTable = async () => {
      await getListData();
      state.dialogObj.show = false;
    };
    return {
      ...toRefs(state),
      handleButton,
      refreshTable,
      handleCurrentChange,
      handleSizeChange,
      getHeatSourceData,
      getHeatStationData,
      getSystemData,
    };
  },
};
</script>
